package com.gxa.hualian.web.servlet;

import com.gxa.hualian.entity.Coupon;
import com.gxa.hualian.entity.User;
import com.gxa.hualian.service.CouponService;
import com.gxa.hualian.service.UserService;
import com.gxa.hualian.service.impl.CouponServiceImpl;
import com.gxa.hualian.service.impl.UserServiceImpl;
import org.apache.poi.hssf.usermodel.*;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;

import java.util.List;

/**
 * 文件下载
 * @author Administrator
 */
@WebServlet(name = "ExportServlet", value = "/export")
public class ExportServlet extends HttpServlet {
    private UserService userService=new UserServiceImpl();
    private CouponService couponService=new CouponServiceImpl();
    public  void userHandler(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取集合
        List<User> users= null;
        try {
            users = userService.sellectAll();
            // 工作簿对象
            HSSFWorkbook workbook = new HSSFWorkbook();
            // 创建工作表
            HSSFSheet sheet = workbook.createSheet("用户列表");
            String fileName = "用户列表.xls";
            // 将文件名中的中文部分被URL编码后的内容进行解析, 最终还是显示为中文状态
            fileName = URLEncoder.encode(fileName,"utf-8").replaceAll("\\+", "%20");
            // headers表示excel表中第一行的表头 在excel表中添加表头
            String[] headers = { "编号", "手机号","注册时间"};
            // 创建一个行对象, 作为表头
            HSSFRow row = sheet.createRow(0);
            for(int i=0;i<headers.length;i++){
                // 在行中添加单元格
                HSSFCell cell = row.createCell(i);
                HSSFRichTextString text = new HSSFRichTextString(headers[i]);
                // 把字段名添加到表头行上
                cell.setCellValue(text);
            }

            //准备将时间格式处理为标准日期格式
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            // 添加数据行:表头信息占用第一行,所有要从1(第二行开始添加)
            int rowNum = 1;
            for (User item : users) {
                HSSFRow dataRow = sheet.createRow(rowNum);
                dataRow.createCell(0).setCellValue(rowNum);
                dataRow.createCell(1).setCellValue(item.getPhone());
                //时间格式赋值
                dataRow.createCell(2).setCellValue(dateFormat.format(item.getRegTime()));
                rowNum++;
            }

            //返回给前端下载
            //指定文档类型
            response.setContentType("application/octet-stream");
            //指定响应头 Content-disposition附件
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            //刷新流
            response.flushBuffer();
            //输出流反给前端
            workbook.write(response.getOutputStream());
        } catch (Exception e) {
            //当有异常发生,当前Servlet不做处理,统一转发给ExceptionServlet
            //利用request作用域对象,将e传递
            request.setAttribute("exception",e);
            //实现转发
            this.getServletContext().getRequestDispatcher("/error").forward(request,response);
        }

    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取请求头exportType 参数
        System.out.println("ExportServlet 被访问了");
//        String exportType=request.getHeader("exportType");
        String exportType=request.getParameter("exportType");
        System.out.println(exportType);
       if ("user".equals(exportType)){
           userHandler(request,response);
       }else if("cpn".equals(exportType)){
           cpnHandler(request,response);
       }

    }

    public  void cpnHandler(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取集合
        List<Coupon> coupons= null;
        try {
            coupons = couponService.sellectAll();
            // 工作簿对象
            HSSFWorkbook workbook = new HSSFWorkbook();
            // 创建工作表
            HSSFSheet sheet = workbook.createSheet("优惠券列表");
            String fileName = "优惠券列表.xls";
            // 将文件名中的中文部分被URL编码后的内容进行解析, 最终还是显示为中文状态
            fileName = URLEncoder.encode(fileName,"utf-8").replaceAll("\\+", "%20");
            // headers表示excel表中第一行的表头 在excel表中添加表头
            String[] headers = { "编号","名称", "领取有效时间","使用有效时间","上下架"};
            // 创建一个行对象, 作为表头
            HSSFRow row = sheet.createRow(0);
            for(int i=0;i<headers.length;i++){
                // 在行中添加单元格
                HSSFCell cell = row.createCell(i);
                HSSFRichTextString text = new HSSFRichTextString(headers[i]);
                // 把字段名添加到表头行上
                cell.setCellValue(text);
            }

            //准备将时间格式处理为标准日期格式
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            // 添加数据行:表头信息占用第一行,所有要从1(第二行开始添加)
            int rowNum = 1;
            for (Coupon item : coupons) {
                HSSFRow dataRow = sheet.createRow(rowNum);
                dataRow.createCell(0).setCellValue(rowNum);
                dataRow.createCell(1).setCellValue(item.getName());
                //时间格式赋值
                dataRow.createCell(2).setCellValue(dateFormat.format(item.getCollectExp()));
                dataRow.createCell(3).setCellValue(dateFormat.format(item.getUsedExp()));
                dataRow.createCell(4).setCellValue(item.getInUsed());
                rowNum++;
            }

            //返回给前端下载
            //指定文档类型
            response.setContentType("application/octet-stream");
            //指定响应头 Content-disposition附件
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            //刷新流
            response.flushBuffer();
            //输出流反给前端
            workbook.write(response.getOutputStream());
        } catch (Exception e) {
            //当有异常发生,当前Servlet不做处理,统一转发给ExceptionServlet
            //利用request作用域对象,将e传递
            request.setAttribute("exception",e);
            //实现转发
            this.getServletContext().getRequestDispatcher("/error").forward(request,response);
        }

    }
}
